package controllers

import (
	"encoding/json"
	"errors"
	// "strconv"
	"github.com/astaxie/beego"
	"gitee.com/lzqysoft/ims/models"
	"reflect"
	"strings"
	//	"fmt"
	"gitee.com/lzqysoft/ims/libs/encrypt"
	"time"
	//	"fmt"
	//	"os"
	//	"path"
)

// DeptController for Dept
type DeptController struct {
	CommonController
}

//URLMapping 方法映射
func (c *DeptController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Update", c.Update)
	c.Mapping("Delete", c.Delete)
	//	c.Mapping("UploadPhoto", c.UploadPhoto)
	c.Mapping("DeleteDepts", c.DeleteDepts)
	c.Mapping("AssignUserDept", c.AssignUserDept)
	c.Mapping("SetDeptDirector", c.SetDeptDirector)
	c.Mapping("GetDeptTree", c.GetDeptTree)
}

// Post  create Dept
// @Title Post
// @Description create Dept
// @Param	body		body 	models.Dept	true		"body for Dept content"
// @Success 201 {int} models.Dept
// @Failure 403 body is empty
// @router / [post]
func (c *DeptController) Post() {
	user := c.User
	// rdata, err := c.AesDecode(c.GetString("tdata"))
	// if err != nil {
	// 	c.RetError(ErrToken)
	// }
	// sdata, _ := rdata.(map[string]interface{})
	var v models.Dept
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	err = json.Unmarshal(rdata, &v)
	// v.Name, _ = sdata["Name"].(string)
	// v.Remark, _ = sdata["Remark"].(string)
	// //	vpid, _ := sdata["Pid"].(string)
	// vstatus, _ := sdata["Status"].(string)
	// v.Status, _ = strconv.Atoi(vstatus)
	// v.Pid = sdata["Pid"].(string)
	// v.Level = 1
	v.Seq = 100
	v.Creater = user.Name
	v.Ctime = time.Now()
	v.Updater = v.Creater
	v.Utime = v.Ctime
	v.Organization = user.Organization
	v.Isdelete = 0
	v.Id = encrypt.GetGuid()
	if _, err := models.AddDept(&v); err == nil {
		c.Dlog("添加了部门，id是：", v.Id)
		c.RetSuccess(v.Id)

	}
	c.RetError(ErrDatabase)
}

// GetOne get Dept by id
// @Title Get
// @Description get Dept by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Dept
// @Failure 403 :id is empty
// @router /:id [get]
func (c *DeptController) GetOne() {
	id := c.GetString(":id")
	v, err := models.GetDeptById(id)
	if err != nil {
		c.RetError(ErrNoData)
	}
	c.RetSuccess(v)
}

// GetAll get Dept列表
// @Title Get All
// @Description get Dept
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Dept
// @Failure 403
// @router / [get]
func (c *DeptController) GetAll() {
	user := c.User

	var fields []string
	var sortby []string
	var order []string
	query := make(map[string]string)
	var limit int64 = -1
	var offset int64
	query["Organization"] = user.Organization.Id
	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	sortby = append(sortby, "Seq")
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	order = append(order, "asc")
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}

	l, err := models.GetAllDept(query, fields, sortby, order, offset, limit)
	if err != nil {
		c.RetError(ErrDatabase)
	}
	//	tree := make(map[string]interface{})
	//	treedata := make([]map[string]interface{}, 0)
	//	org, _ := models.GetOrganizationById(user.OrgId)
	//	tree["org_id"] = user.OrgId
	//	tree["id"] = user.OrgId
	//	tree["expand"] = true
	//	tree["title"] = org.Name
	//	tree["children"] = models.GetDeptTreeByParentIdAndOrgId(0, user.OrgId)
	//	treedata = append(treedata, tree)
	//udtree, _ := models.GetUserDeptTree(user.Organization.Id)
	tabledata := make(map[string]interface{})
	//tabledata["treedata"] = udtree
	tabledata["tabledata"] = l
	c.RetSuccess(tabledata)
}

// Update update the Dept
// @Title Update
// @Description update the Dept
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Dept	true		"body for Dept content"
// @Success 200 {object} models.Dept
// @Failure 403 :id is not int
// @router /Update [post]
func (c *DeptController) Update() {
	user := c.User
	// rdata, err := c.AesDecode(c.GetString("tdata"))
	// if err != nil {
	// 	c.RetError(ErrToken)
	// }
	// sdata, _ := rdata.(map[string]interface{})
	// id := sdata["Id"].(string)
	//	id, _ := strconv.ParseInt(sid, 10, 64)
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	var u models.Dept
	err = json.Unmarshal(rdata, &u)

	v, _ := models.GetDeptById(u.Id)
	// v.Name = u.Name
	// v.Remark = u.Remark
	// v.Status = u.Status
	// v.Pid = u.Pid
	// v.Name, _ = sdata["Name"].(string)
	// v.Remark, _ = sdata["Remark"].(string)
	// //	vpid, _ := sdata["Pid"].(string)
	// vstatus, _ := sdata["Status"].(string)
	// v.Status, _ = strconv.Atoi(vstatus)
	// v.Pid, _ = sdata["Pid"].(string)
	// vseq, _ := sdata["Seq"].(string)

	// v.Seq, _ = strconv.Atoi(vseq)
	u.Updater = user.Name
	u.Utime = time.Now()
	u.Organization = user.Organization
	beego.Debug(v.Status)
	err = models.UpdateDeptById(&u)
	if err != nil {
		beego.Error(err)
		c.RetError(ErrDatabase)
	}
	c.Dlog("修改了部门信息,部门id为：", v.Id, 1, v)
	c.RetSuccess(v.Id)
}

// Delete delete the Dept
// @Title Delete
// @Description delete the Dept
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /Delete [post]
func (c *DeptController) Delete() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	id := sdata["Id"].(string)
	//	id, err := strconv.ParseInt(sid, 10, 64)
	if err, rs := models.GetDeptByPid(id); err == nil && len(rs) > 0 {
		c.RetError(ErrPid)
	}
	if _, err := models.GetUserByDept(id); err == nil {
		c.RetError(ErrPid)
	}
	if err := models.SoftDeleteDept(id, user.Name); err == nil {
		c.Dlog("删除了系统资源", id)
		c.RetSuccess(id)
	}
	c.RetError(ErrDatabase)
}

// DeleteDepts 删除多个dept
// @Title DeleteDepts
// @Description DeleteDepts
// @Success 200
// @Failure 403
// @router /DeleteDepts [post]
func (c *DeptController) DeleteDepts() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.([]interface{})
	for _, value := range sdata {
		id := value.(string)
		//		id, _ := strconv.ParseInt(eid, 10, 64)
		err := models.SoftDeleteDept(id, user.Name)
		if err != nil {
			c.RetError(ErrDatabase)
		}
		c.Dlog("删除了部门，id为：", id)

	}
	c.RetSuccess(sdata)
}

// AssignUserDept 分配部门人员
// @Title AssignUserDept
// @Description 分配部门人员
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /AssignUserDept [post]
func (c *DeptController) AssignUserDept() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	//	beego.Debug("rdatardatardata:", rdata)
	if err != nil {
		c.RetError(ErrToken)
	}
	err = models.DeleteUserDeptByOrg(user.Organization.Id)

	if err != nil {
		//		beego.Debug(err)
		c.RetError(ErrDatabase)
	}

	sdata, _ := rdata.([]interface{})
	for _, e := range sdata {
		ud := e.(map[string]interface{})
		if !ud["isParent"].(bool) && !ud["isHidden"].(bool) {
			userid := ud["id"].(string)
			tp := reflect.TypeOf(ud["pId"])
			beego.Debug(userid)
			deptid := ""
			if tp.Name() != "string" {
				deptid = models.GetTopDept(userid)
			} else {
				deptid = ud["pId"].(string)
			}
			_, err = models.AddUserDept(deptid, userid)
			//			beego.Debug("err is :", v, err)
			c.Dlog("添加了用户部门关系，用户id为:", userid)
		}
	}

	//	beego.Debug("sdatasdatasdatasdata:", sdata)
	//	beego.Debug("sdatasdatasdatasdata:", reflect.TypeOf(sdata))
	//	sid, _ := sdata["Roleid"].(float64)
	//	if err := models.DeleteUserDeptByOrg(user.OrgId); err == nil {
	//		c.Data["json"] = "OK"
	//	} else {
	//		c.Data["json"] = err.Error()
	//	}
	c.RetSuccess("ok")
}


// SetDeptDirector 设置部门主管
// @Title SetDeptDirector
// @Description 设置部门主管
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /SetDeptDirector [post]
func (c *DeptController) SetDeptDirector() {
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	fdata, ok := rdata.(map[string]interface{})
	if !ok {
		c.RetError(ErrInputData)
	}
	DeptId, ok := fdata["DeptId"].(string)
	if !ok {
		c.RetError(ErrInputData)
	}
	UserId, ok := fdata["UserId"].(string)
	if !ok {
		c.RetError(ErrInputData)
	}
	dept, err := models.GetDeptById(DeptId)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	user, err := models.GetUserById(UserId)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	dept.Director = user.Id
	if err = models.UpdateDeptById(dept); err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	c.RetSuccess("")
}


// GetDeptTree get Dept tree
// @Title Get All
// @Description GetDeptTree
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Dept
// @Failure 403
// @router /GetDeptTree [get]
func (c *DeptController) GetDeptTree() {
	user := c.User
	nodes, _ := models.GetUserDeptTreeByDeptId(user.Organization.Id, user.Dept[0].Id)

	tabledata := make(map[string]interface{})
	tabledata["treedata"] = nodes
	c.RetSuccess(tabledata)
}